<template>
	<view class="container">
		<navbar :background="background" :bgSize='bgSize' :showBack="false" :headType="1">
			<view class="nav-con">
				<view class="manage" v-if='list.length > 0 && Authorization' @tap='delHandle'>
					{{isDelFlag ? '退出管理':'管理'}}
				</view>
				<view class="title">购物车</view>
			</view>
		</navbar>
		<view class="linear-goods-list-bg">
			<image :src='hostUrl+"/static/images/cart_bg.png"'></image>
		</view>
		<view class="wrap">
			<view class="cart-wrap">
				<template v-if='showCartData'>
					<view class="cart-con" v-if='list.length > 0 && Authorization'>
						<template>
							<view class="cart-item" v-for='(item,index) in list'>
								<template v-if='!isDelFlag'>
									<view class="cart-select line-v-center" @tap.stop='selectGoods(index)'
										v-if='(item.stock_status == 1 || item.stock_status == 3) && item.goods.status != 20'>
										<image
											:src='item.is_checked ?"/static/cart-checked.png":"/static/cart-check.png"'>
										</image>
									</view>
									<view class="cart-select line-v-center" v-else>
										<image src='/static/cart-disabled.png'></image>
									</view>
								</template>
								<template v-else>
									<view class="cart-select line-v-center" @tap.stop='selectGoods(index)'>
										<image
											:src='item.is_checked ?"/static/cart-checked.png":"/static/cart-check.png"'>
										</image>
									</view>
								</template>
								<view class="cart-goods-img" @tap='toGoodsDetial(index,item.goods_id)'>
									<image
										:src='item.goods.skuInfo.image ? item.goods.skuInfo.image : item.goods.goods_image'
										mode="aspectFit"></image>
									<template v-if='item.goods.status == 20'>
										<view class="no-stock-tip line-center">已下架</view>
									</template>
									<template v-else>
										<view class="no-stock-tip line-center" v-if='item.stock_status == 2'>补货中</view>
									</template>
								</view>
								<view class="cart-goods-info">
									<view class="cart-goods-name" @tap='toGoodsDetial(index,item.goods_id)'>
										{{item.goods.goods_name}}
									</view>
									<view class="cart-goods-attr ellipsis" @tap='toGoodsDetial(index,item.goods_id)'>
										{{item.goods.skuInfo.spec_value_names}}
									</view>
									<view class="cart-goods-b line-v-center">
										<view class="cart-goods-price-wrap" @tap='toGoodsDetial(index,item.goods_id)'>
											<view class="cart-goods-price">
												<text>￥</text>{{item.goods.skuInfo.goods_price}}<text v-if='item.goods.skuInfo.goods_unit' class="unit">/{{item.goods.skuInfo.goods_unit}}</text></text>
											</view>
											<view class="cart-goods-price-line">￥{{item.goods.skuInfo.market_price}}
											</view>
										</view>
										<template v-if='item.goods.status == 10'>
											<view class="number-box line-v-center"
												v-if='item.stock_status == 1 || item.stock_status == 3'>
												<view class="mins h-number" @tap.stop='bindMins(index,item)'
													:style="{opacity:item.mins_op}">
													<image src='/static/mins.png'></image>
												</view>
												<view class="number-con">
													<input type='number' v-model="item.goods_num"
														oninput="value = value.replace(/\s/g, '')"
														@blur="getVal($event,item,index)" />
												</view>
												<!-- <view class="number-con">{{item.goods_num}}</view> -->
												<view class="plus h-number" @tap.stop='bindPlus(index,item)'
													:style="{opacity:item.plus_op}">
													<image src='/static/plus.png'></image>
												</view>
											</view>
											<view class="line-center number-box-no" v-else>
												暂无库存
											</view>
										</template>
										<template v-else>
											<view class="line-center number-box-no" v-if='item.goods.status == 20'>
												下架商品
											</view>
										</template>
									</view>
								</view>
							</view>
						</template>
					</view>
					<view class="no-data-wrap" v-else>
						<no-data text='购物车还是空的,赶紧行动吧!' noDataImg='/static/no-cart.png'></no-data>
					</view>
				</template>
			</view>
		</view>
		<view class="footer" :style="{bottom:fixedBottom+'px'}" v-if='list.length > 0 && Authorization'>
			<view class="footer-select line-v-center" @tap='selectAll'>
				<image :src='allChecked ? "/static/cart-checked.png":"/static/cart-check.png"'></image>
				<text>全选</text>
			</view>
			<template v-if='!isDelFlag'>
				<view class="center-wrap">
					<view class="total-price">
						合计：<text>¥{{totalPrice}}</text>
					</view>
					<view class="total-count">
						已选<text>{{selectNum}}</text>件
					</view>
				</view>
				<view class="sure line-center" @tap='toSettle'>去结算</view>
			</template>
			<template v-else>
				<view class="center-wrap"></view>
				<button class="sure line-center" @tap='delCart'>删除</button>
			</template>
		</view>
		<view class="toast-wrap" v-if='showToast'>
			<view class="toast-con">{{cartErrText}}</view>
		</view>
	</view>
</template>

<script>
	import debounce from '../../../utils/debounce.js';
	const app = getApp();
	export default {
		data() {
			return {
				platform: app.getPlatform(),
				background: `url(${app.globalData.hostUrl}/static/images/cart_bg.png)`,
				bgSize: '100% 344rpx',
				hostUrl: app.globalData.hostUrl,
				fixedBottom: 0,
				Authorization: '',
				list: [],
				haveStockList: [],
				noStockList: [],
				allChecked: false,
				selectNum: 0,
				totalPrice: 0,
				isDelFlag: false,
				cartErrText: '',
				showToast: false,
				showCartData: false,
			};
		},
		onShow() {
			this.Authorization = uni.getStorageSync('TOKEN') ? uni.getStorageSync('TOKEN') : "";
			this.showCartData = false;
			this.selectNum = 0;
			this.totalPrice = 0;
			this.allChecked = false;
			this.isDelFlag = false;
			this.getList();
		},
		onPullDownRefresh() {
			this.showCartData = false;
			this.selectNum = 0;
			this.totalPrice = 0;
			this.allChecked = false;
			this.getList();
			uni.stopPullDownRefresh()
		},
		onLoad() {
			if (this.platform === 'mp') {
				this.fixedBottom = 0;
			} else {
				this.fixedBottom = 50;
			}
		},
		methods: {
			clearData(){
				this.selectNum = 0;
				this.totalPrice = 0;
				this.allChecked = false;
				this.getList('check');
			},
			getList(check = '') {
				const that = this;
				app.globalRequest({
					api: app.getApi().goods.cartList,
					method: 'POST',
					data:{
						check,
					}
				}).then(res => {
					that.showCartData = true;
					if (res.code == 0) {
						res.data.forEach(v => {
							v.is_checked = false;
							//加购数量大于/等于库存数量
							if (v.goods_num >= v.goods.skuInfo.stock_num) {
								v.plus_op = 0.4;
								// v.goods_num = v.goods.skuInfo.stock_num;
							} else {
								v.plus_op = 1;
							}
							//加购数量小于/等于库存数量
							if (v.goods_num <= v.goods.skuInfo.minimum) {
								console.log('添加商品数量小于等于最低起卖数量，减号置灰')
								v.mins_op = 0.4;
								// v.goods_num = v.goods.skuInfo.minimum;
							} else if (v.goods_num == v.goods.skuInfo.stock_num) {
								console.log('添加商品数量和库存相等，减号不置灰')
								if (v.goods_num == v.goods.skuInfo.stock_num == 1) {
									console.log('添加商品数量和库存相等，且 数量都为1，减号置灰')
									v.mins_op = 0.4;
								}
								v.mins_op = 1;
							} else {
								v.mins_op = 1;
							}
						})
						that.initList(res.data);
					}
				})
			},
			initList(arr) {
				const that = this;
				const haveStockList = arr.filter(v => {
					return (v.stock_status == 1 || v.stock_status == 3) && v.goods.status != 20
				})
				const noStockList = arr.filter(v => {
					return v.stock_status == 2 || v.goods.status == 20
				})
				that.list = [...haveStockList, ...noStockList];
				that.haveStockList = haveStockList;
				console.log('noStockList',noStockList)
				console.log('that.list 更新', that.list)
				console.log('that.haveStockList 更新', that.haveStockList)
			},
			delHandle() {
				this.isDelFlag = !this.isDelFlag;
				if (this.isDelFlag) { //
					console.log('delHandle  在管理状态')
					if (this.allChecked) {
						this.list.forEach(v => {
							v.is_checked = true;
						})
					}
				} else {
					if (this.allChecked) {
						this.list.forEach(v => {
							if (v.stock_status == 1 || v.stock_status == 3) {
								v.is_checked = true;
							} else {
								v.is_checked = false;
							}
						})
						this.selectNum = this.haveStockList.length;
						console.log('this.list', this.list)
					}

				}
			},
			//选择商品
			selectGoods(index) {
				let list = this.list,
					allChecked = this.allChecked,
					selectNum = this.selectNum;
				if (list[index].is_checked) {
					list[index].is_checked = false;
					allChecked = false;
					selectNum--;
				} else {
					list[index].is_checked = true;
					if (list[index].stock_status == 1 || list[index].stock_status == 3) {
						selectNum++;
					}
					if (!this.isDelFlag) {
						if (selectNum == this.haveStockList.length) {
							allChecked = true;
						}
					} else {
						allChecked = list.every(v => {
							return v.is_checked === true
						})
					}
				}
				console.log('allChecked', allChecked)
				console.log('selectNum selectGoods方法', selectNum)
				this.list = list;
				this.allChecked = allChecked;
				this.selectNum = selectNum;
				this.getCartTotalPrice()
			},
			//全选
			selectAll() {
				let selectNum = this.selectNum;
				if (this.allChecked) {
					this.allChecked = false;
					this.list.forEach(v => {
						v.is_checked = false;
					})
					selectNum = 0;
					this.totalPrice = 0;
				} else {
					this.allChecked = true;
					if (!this.isDelFlag) {
						console.log('全选 退出管理状态')
						this.list.forEach(v => {
							if (v.stock_status == 1 || v.stock_status == 3) {
								v.is_checked = true;
							} else {
								v.is_checked = false;
							}
						})
						selectNum = this.haveStockList.length;
					} else {
						console.log('全选 在管理状态')
						this.list.forEach(v => {
							v.is_checked = true;
						})
						selectNum = this.list.length;
					}
					this.getCartTotalPrice()
				}
				this.selectNum = selectNum;
			},
			//更新购买数量
			editCart(index, item) {
				const that = this;
				let list = that.list;
				app.globalRequest({
					api: app.getApi().goods.editCart,
					method: 'POST',
					data: {
						goodsId: item.goods_id,
						goodNum: item.goods_num,
						goodsSkuId: item.goods_sku_id
					}
				}).then(res => {
					if (res.code == 0) {
						const total_price = parseFloat(item.goods_num) * parseFloat(item.goods.skuInfo
							.goods_price);
						item.total_price = total_price.toFixed(2);
						if (item.is_checked) that.getCartTotalPrice();
						// this.getCartTotalPrice();
					} else if (res.code == 213) {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
						list[index].stock_status = res.data.stock_status;
						list[index].goods.skuInfo.stock_num = res.data.stock
						if (res.data.stock_status == 3) {
							list[index].goods_num = res.data.stock;
							list[index].plus_op = '0.4'
						}
						console.log('list', list)
						// that.initList(list)
						that.clearData()
					}
				})
			},
			//获取购物车总价格
			getCartTotalPrice() {
				let that = this,
					selectGoodsIds = '',
					selectGoodsIdsArr = [];
				const selectGoodsList = this.getSelectGoods();
				selectGoodsList.forEach(v => {
					if (v.stock_status == 1 || v.stock_status == 3) {
						selectGoodsIdsArr.push(v.id)
					}
				})
				console.log('selectGoodsIdsArr', selectGoodsIdsArr)
				selectGoodsIds = selectGoodsIdsArr.join(',');
				console.log('selectGoodsIds 总价=======', selectGoodsIds)
				app.globalRequest({
					api: app.getApi().goods.cartTotalPrice,
					data: {
						cartIds: selectGoodsIds,
					}
				}).then(res => {
					if (res.code == 0) {
						that.totalPrice = res.totalPrice
					} else if (res.code == 10031) {
						uni.showModal({
							title: '提示',
							content: res.msg,
							showCancel:false,
							success: function(res) {
								if (res.confirm) {
									console.log('用户点击确定');
									that.clearData()
									// that.getList();
									// that.allChecked = false;
									// that.selectNum = 0;
								}
							}
						})
					} else {
						uni.showToast({
							title: res.msg,
							duration: 2000,
							icon: 'none'
						})
					}
				})
			},
			getVal(e, item, index) {
				console.log('e ===> getVal', e)
				item.goods_num = '';
				if (e.detail.value) {
					item.goods_num = e.detail.value;
					if (Number(e.detail.value) >= item.goods.skuInfo.stock_num) {
						item.goods_num = item.goods.skuInfo.stock_num;
						item.plus_op = 0.4;
						item.mins_op = 1;
					} else if (Number(e.detail.value) <= item.goods.skuInfo.minimum) {
						item.goods_num = item.goods.skuInfo.minimum;
						item.mins_op = 0.4;
						item.plus_op = 1;
					} else {
						item.plus_op = 1;
						item.mins_op = 1;
					}
					this.editCart(index, item);
				}
			},
			//获取选中商品
			getSelectGoods() {
				let selectGoodsList = this.list.filter(v => {
					return v.is_checked == true
				})
				console.log('selectGoodsList', selectGoodsList)
				return selectGoodsList;
			},
			bindPlus(index, item) {
				let list = this.list;
				if (list[index].goods_num >= list[index].goods.skuInfo.stock_num) {
					return;
				}
				list[index].goods_num++;
				list[index].mins_op = '1';
				if (list[index].goods_num >= list[index].goods.skuInfo.stock_num) {
					list[index].goods_num = list[index].goods.skuInfo.stock_num;
					list[index].plus_op = '0.4';
				}
				this.editCart(index, item);
				// this.list = list;
				// this.editCart(item);
			},
			bindMins(index, item) {
				let list = this.list;
				if (list[index].goods_num <= list[index].goods.skuInfo.minimum) {
					uni.showToast({
						title: `最低起卖数量不小于${list[index].goods.skuInfo.minimum}`,
						icon: 'none',
						duration: 2000
					})
					return;
				}
				list[index].goods_num--;
				list[index].plus_op = '1';
				if (list[index].goods_num <= list[index].goods.skuInfo.minimum) {
					list[index].goods_num = list[index].goods.skuInfo.minimum;
					list[index].mins_op = '0.4';
				}
				this.list = list;
				this.editCart(index, item);
				// this.editCart(item);
			},
			delCart() {
				let that = this,
					list = this.list,
					selectGoodsIds = '';
				const selectGoodsList = this.getSelectGoods();
				var selectGoodsIdsArr = selectGoodsList.map(v => {
					return v.id
				})
				if (selectGoodsIdsArr.length == 0) {
					uni.showToast({
						title: '没有选中的商品',
						icon: 'none'
					})
					return;
				}
				selectGoodsIds = selectGoodsIdsArr.join(',');
				console.log('selectGoodsIds 删除', selectGoodsIds)
				uni.showModal({
					title: '提示',
					content: `确认要删除这${selectGoodsIdsArr.length}件产品吗？`,
					cancelText: '我再想想',
					confirmColor: '#5DC751',
					success(res) {
						console.log('res', res)
						if (res.confirm) {
							app.globalRequest({
								api: app.getApi().goods.clearCart,
								method: 'POST',
								data: {
									cartIds: selectGoodsIds,
								}
							}).then(res => {
								if (res.code == 0) {
									uni.showToast({
										title: res.msg,
										duration: 2000,
									})
									const newList = list.filter(v => {
										return v.is_checked == false
									})
									that.list = newList
								} else {
									uni.showToast({
										title: res.msg,
										duration: 2000,
									})
								}
							})
						}
					}
				})
			},
			//获取用户信息
			async getUserInfo() {
				let that = this;
				return await new Promise((resolve, reject) => {
					app.globalRequest({
						api: app.getApi().user.getUserInfo,
					}).then(res => {
						resolve(res.data)
					}).catch(err => {
						reject(err)
					})
				})

			},
			async toSettle() {
				let selectGoods = this.getSelectGoods();
				let selectGoodsIdsArr = [];
				selectGoods.forEach(v => {
					if (v.stock_status == 1 || v.stock_status == 3) {
						selectGoodsIdsArr.push(v.id)
					}
				})
				console.log('selectGoodsIdsArr', selectGoodsIdsArr)
				if (selectGoodsIdsArr.length == 0) {
					uni.showToast({
						title: '没有选中的商品',
						icon: 'none'
					})
					return;
				}
				const selectGoodsIds = selectGoodsIdsArr.join(',');
				console.log('selectGoodsIds 结算', selectGoodsIds)
				app.globalRequest({
					api: app.getApi().goods.cartCheck,
					method: 'POST',
					data: {
						cartIds: selectGoodsIds,
						mode: 'cart',
						couponId:0,
						share_id:0,
					}
				}).then(res => {
					if (res.code == 0) {
						uni.navigateTo({
							url: `/pages/goods-page/submit-order/submit-order?cart_ids=${selectGoodsIds}&mode=cart`
						})
					} else {
						this.showToast = true;
						this.cartErrText = res.msg;
						setTimeout(() => {
							this.showToast = false;
						}, 2000)
						this.clearData()
					}
				})

			},
			toGoodsDetial(index,id) {
				let status = this.list[index].goods.status;
				if(status == 20){
					return;
				}
				uni.navigateTo({
					url: `/pages/goods-page/goods-detail/goods-detail?goods_id=${id}`
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.nav-con {
		width: 100%;
		height: 100%;
		color: #fff;
		display: flex;
		align-items: center;
		position: relative;
		padding-left: 24rpx;
		box-sizing: border-box;

		.title {
			width: 300rpx;
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
			text-align: center;
			font-size: 30rpx;
			font-weight: bold;
			position: absolute;
			left: 50%;
			top: 50%;
			transform: translate(-50%, -50%);
			transition: color linear 0.3s;
		}
	}

	.wrap {
		padding: 24rpx 0 150rpx;
		position: relative;
		z-index: 2;
	}

	.cart-wrap {
		margin: 0 24rpx;
		border-radius: 16rpx;
		background: #fff;
		min-height: 950rpx;
	}

	.cart-item {
		padding: 28rpx 24rpx 28rpx 18rpx;
		border-bottom: 2rpx solid #f9f9f9;
		display: flex;

		&:last-of-type {
			border-bottom: 0;
		}

		.cart-select {
			width: 48rpx;
			height: 180rpx;

			image {
				width: 100%;
				height: 48rpx;
			}
		}

		.cart-goods-img {
			width: 180rpx;
			height: 180rpx;
			border-radius: 16rpx;
			overflow: hidden;
			margin: 0 16rpx;
			position: relative;

			image {
				width: 100%;
				height: 100%;
			}

			.no-stock-tip {
				width: 128rpx;
				height: 60rpx;
				background: rgba(0, 0, 0, 0.74);
				border-radius: 30rpx;
				position: absolute;
				left: 0;
				right: 0;
				top: 0;
				bottom: 0;
				z-index: 22;
				margin: auto;
				color: #fff
			}
		}

		.cart-goods-info {
			flex: 1;
			overflow: hidden;

			.cart-goods-name {
				width: 100%;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
				padding-top: 10rpx;
			}

			.cart-goods-attr {
				width: 100%;
				font-size: 24rpx;
				color: #AFB0B2;
				padding-top: 16rpx;

			}

			.cart-goods-b {
				justify-content: space-between;
				margin-top: 20rpx;

				.cart-goods-price-wrap {
					// display: flex;
					// align-items: baseline;

					.cart-goods-price {
						color: #FF5040;
						font-size: 32rpx;

						text {
							font-size: 24rpx;
						}
						.unit{
							color: #AFB0B2;
						}
					}

					.cart-goods-price-line {
						transform-origin: left top;
						font-size: 20rpx;
						color: #AFB0B2;
						padding-left: 4rpx;
						text-decoration: line-through;
					}
				}
			}

			.number-box {
				width: 154rpx;
				height: 44rpx;
				background: #F2F4F7;
				border-radius: 22rpx;
				justify-content: space-between;

				.h-number {
					width: 44rpx;
					height: 44rpx;
					border-radius: 100%;
					display: flex;
					align-items: center;
					justify-content: center;
					flex-shrink: 0;

					image {
						width: 20rpx;
						height: 20rpx;
					}
				}
			}

			.number-box-no {
				width: 154rpx;
				height: 44rpx;
				background: #F2F4F7;
				border-radius: 22rpx;
				color: #AFB0B2;
				font-size: 24rpx;
			}

			.number-con {
				input {
					text-align: center;
					font-size: 28rpx;
				}
			}
		}
	}

	.no-data-wrap {
		margin: 0 24rpx;
		border-radius: 16rpx;
		background: #fff;
		padding-top: 140rpx;
	}

	.footer {
		width: 100%;
		height: 120rpx;
		padding: 0 24rpx 0 18rpx;
		box-sizing: border-box;
		display: flex;
		align-items: center;
		background: #FFFFFF;
		position: fixed;
		left: 0;
		z-index: 22;

		.footer-select {
			height: 48rpx;

			image {
				width: 48rpx;
				height: 100%;
			}
		}

		.center-wrap {
			flex: 1;
			display: flex;
			flex-direction: column;
			align-items: flex-end;
			font-size: 24rpx;
			margin-right: 20rpx;

			.total-price {
				color: #FF5040;
				font-family: DIN-BOLD;

				text {
					font-size: 36rpx;
				}
			}

			.total-count {
				color: #AFB0B2;

				text {
					padding: 0 6rpx;
				}
			}
		}

		.sure {
			min-width: 200rpx;
			height: 88rpx;
			border-radius: 16rpx 16rpx 16rpx 16rpx;
			padding: 0 10rpx;
			box-sizing: border-box;
			background: $supplier-btn-linear-color;
			color: #fff;
			font-size: 28rpx;
		}
	}

	.toast-wrap {
		width: 100%;
		height: 100%;
		background: rgba(255, 255, 255, 0.1);
		position: fixed;
		lef: 0;
		top: 0;
		z-index: 35;
		display: flex;
		align-items: center;
		justify-content: center;

		.toast-con {
			max-width: 600rpx;
			padding: 14rpx 20rpx;
			background: rgba(0, 0, 0, 0.7);
			border-radius: 6rpx;
			color: #fff;
			font-size: 24rpx;
		}
	}
</style>